<template>
  <brand-background>
    <template #page>
      <div class="login">
        <div class="form-wrapper">
          <div class="tab-box">
            <div :class="[{ 'tab--active': state.loginType === 1 }, 'tab']" @click="changeType(1)">学生账号</div>
            <div :class="[{ 'tab--active': state.loginType == 2 }, 'tab']" @click="changeType(2)">教师账号</div>
          </div>
          <!-- 学生账号 -->
          <a-form v-if="state.loginType === 1" ref="formRef" class="login-form" :model="form" :rules="rules" name="form" @finish="onFinish">
            <a-form-item name="number">
              <a-input v-model:value="form.number" v-trim size="large" style="width: 360px" placeholder="学号" :autocomplete="'on'" />
            </a-form-item>
            <a-form-item name="password">
              <a-input
                v-model:value="form.password"
                v-trim
                type="password"
                style="width: 360px"
                size="large"
                placeholder="密码"
                :autocomplete="'on'"
              />
            </a-form-item>
            <a-form-item name="code">
              <div class="auth-code-wrapper">
                <a-input v-model:value="form.code" v-trim size="large" style="width: 265px" placeholder="请输入验证码" />
                <div class="verification-img">
                  <img v-if="accountKaptcha" :src="accountKaptcha" alt="" @click="getKaptchaFn" />
                </div>
              </div>
            </a-form-item>
            <div class="fbc">
              <!-- <span class="forgot-password" @click="router.push('/find-password')">忘记密码</span>
              <span class="forgot-password" @click="router.push('/register')">账号注册</span> -->
            </div>
            <a-button block html-type="submit" size="large" class="btn-submit" :loading="loading">登录</a-button>
          </a-form>
          <!-- 教师登录 -->
          <a-form v-else ref="teacherFormRef" class="login-form" :model="teacherForm" :rules="teacherRules" name="form" @finish="onFinish">
            <a-form-item name="number">
              <a-input
                v-model:value="teacherForm.number"
                v-trim
                size="large"
                style="width: 360px"
                placeholder="工号"
                :autocomplete="'on'"
              />
            </a-form-item>
            <a-form-item name="password">
              <a-input
                v-model:value="teacherForm.password"
                v-trim
                type="password"
                style="width: 360px"
                size="large"
                placeholder="密码"
                :autocomplete="'on'"
              />
            </a-form-item>
            <a-form-item name="code">
              <div class="auth-code-wrapper">
                <a-input v-model:value="teacherForm.code" v-trim size="large" style="width: 265px" placeholder="请输入验证码" />
                <div class="verification-img">
                  <img v-if="accountKaptcha" :src="accountKaptcha" alt="" @click="getKaptchaFn" />
                </div>
              </div>
            </a-form-item>
            <a-button size="large" block html-type="submit" class="btn-submit" :loading="smsLoading">登录</a-button>
          </a-form>
          <!-- 其他方式TODO: 微信，暂时隐藏 -->
          <!-- <div class="other-login-type">
            <p class="separated-line"></p>
          </div>
          <a-button :loading="weixinLoading" size="large" block class="iconfont icon-with-btn" @click="wxLogin">
            <template #icon><i class="iconfont icon-wechat-fill weixin"></i></template>
            微信扫码
          </a-button> -->
        </div>
      </div>
    </template>
  </brand-background>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { Rule } from 'ant-design-vue/es/form'
  import { regex, useCountDown, useSM4 } from 'g6-fn'
  import { onMounted, reactive, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import { SM4_KEY } from '@/config'
  import { loginApi } from '@/services/api'
  import { useUserInfoStore } from '@/store'

  import BrandBackground from '../components/BrandBackground.vue'

  interface TeacherForm {
    number?: number
    code?: number
    password?: number
    securityCode?: number
  }

  const route = useRoute()
  const router = useRouter()
  const userInfoStore = useUserInfoStore()
  const { counter, start } = useCountDown()
  const { encrypt } = useSM4(SM4_KEY)

  /**
   * tab
   */
  const state = reactive({
    loginType: 1
  })
  const changeType = (type: number) => {
    state.loginType = type
  }

  /* 登陆之后的统一操作 */
  const loginAfter = async (token: string) => {
    userInfoStore.changeToken(token)
    await userInfoStore.getUserInfo()
    await userInfoStore.getMenuData()

    const redirectUrl = route.query.redirectUrl ? decodeURIComponent(route.query.redirectUrl as string) : ''
    // 有重定向地址，则携带token到对应的网站
    if (redirectUrl) {
      // 如果其他页面是往该平台首页跳转，则不携带token
      if (redirectUrl === '/') {
        location.href = redirectUrl
        return
      }

      location.href = `${redirectUrl}?token=${token}`
      return
    }

    router.replace('/')
  }

  /**
   * 账号密码登录
   */
  const formRef = ref<any>(null)
  const form = reactive({
    number: undefined,
    password: undefined,
    code: undefined,
    securityCode: undefined
  })
  const rules = reactive<Record<string, Rule[]>>({
    number: [{ required: true, message: '请输入学号', trigger: 'change' }],
    password: [{ required: true, message: '请输入密码', trigger: 'change' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'change' }]
  })
  const { loading, runAsync: submit } = useRequest<ResponseData<any>>(loginApi.loginPwd, {
    onSuccess: async res => {
      await loginAfter(res.data.token)
    },
    onError: () => {
      form.code = undefined
      getKaptchaFn()
    }
  })
  const onFinish = () => {
    let params
    if (state.loginType === 1) {
      params = JSON.parse(JSON.stringify(form))
    }
    if (state.loginType === 2) {
      params = JSON.parse(JSON.stringify(teacherForm))
    }
    // 加密密码
    params.password = encrypt(params.password)
    params.role = state.loginType
    submit(params)
  }

  /**
   * 短信验证码登录
   */
  const teacherFormRef = ref<any>(null)
  const teacherForm = reactive<TeacherForm>({
    number: undefined,
    code: undefined,
    password: undefined,
    securityCode: undefined
  })
  const teacherRules = reactive<Record<string, Rule[]>>({
    number: [{ required: true, message: '请输入工号' }],
    password: [{ required: true, message: '请输入密码', trigger: 'change' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'change' }]
  })
  // const { runAsync: runSendSms } = useRequest<{ headers: { 'security-code': number } }>(loginApi.sendSms, {
  //   onSuccess(data) {
  //     teacherForm.securityCode = data.headers['security-code']
  //     message.success('短信验证码发送成功')
  //     start(60)
  //   }
  // })
  // const sendSms = async () => {
  //   await teacherFormRef.value.validateFields(['tel'])
  //   let params = {
  //     tel: teacherForm.tel,
  //     messageType: 1
  //   }
  //   runSendSms(params)
  // }
  const { loading: smsLoading, runAsync: smsSubmit } = useRequest<ResponseData<any>>(loginApi.loginCode, {
    onSuccess: async res => {
      await loginAfter(res.data.token)
    }
  })
  // const onSmsFinish = () => smsSubmit(teacherForm)

  /**
   * 微信登录
   */
  const { loading: weixinLoading, runAsync: runWxLogin } = useRequest(loginApi.generateWxQrCode)
  const wxLogin = async () => {
    const params = {
      redirectUrl: window.location.origin + '/login-mid-page'
    }
    const res = (await runWxLogin(params)) as any
    if (res) {
      window.location = res.data
    } else {
      message.error(res?.message)
    }
  }

  /**
   * 图形验证码
   */
  const config = {
    isResponseAll: true,
    headers: {
      'Kaptchat-Type': 'LOGIN'
    },
    responseType: 'arraybuffer'
  }

  const accountKaptcha = ref('')

  const { runAsync: getKaptchaFn } = useRequest<{ headers: { 'security-code': undefined }; data: any }>(
    () => loginApi.getKaptcha({}, config),
    {
      onSuccess: res => {
        form.securityCode = res.headers['security-code']
        teacherForm.securityCode = res.headers['security-code']
        accountKaptcha.value =
          'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      }
    }
  )

  onMounted(() => {
    getKaptchaFn()
  })
</script>

<style lang="less" scoped>
  @import '../styles/index.less';

  .login {
    display: flex;
    justify-content: center;
    // height: 100vh;
    height: 100%;
    background-color: @background1;
    flex-direction: column;

    .form-wrapper {
      margin: 0 auto;
      width: 360px;
      height: 480px;

      .tab-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        color: @text04;
        .font20b();

        .tab {
          position: relative;
          padding-left: 24px;
          width: 50%;
          text-align: start;
          cursor: pointer;

          &::after {
            position: absolute;
            top: 50%;
            left: 0;
            display: block;
            width: 1px;
            height: 20px;
            background: @border1;
            transform: translateY(-50%);
            content: '';
          }

          &:first-child {
            padding-right: 24px;
            text-align: end;

            &::after {
              display: none;
            }
          }

          &--active {
            position: relative;
            margin-top: 1px;
            color: @text01;
          }
        }
      }

      .login-form {
        padding: 36px 0 0;

        .ant-form-item {
          margin-bottom: 24px;

          &:nth-child(3) {
            margin-bottom: 0;
            .auth-code-wrapper();
          }
        }
      }

      .forgot-password {
        display: inline-block;
        margin-top: 8px;
        color: @link;
        cursor: pointer;
      }

      .other-login-type {
        .separated-line {
          position: relative;
          margin: 50px 0 26px;
          border-bottom: 1px solid @border1;

          &::after {
            position: absolute;
            top: 0;
            left: 50%;
            width: 116px;
            height: 22px;
            text-align: center;
            color: @text03;
            background: @background1;
            content: '其他登录方式';
            transform: translate(-50%, -50%);
            .font14();
          }
        }
      }

      .weixin {
        font-size: 20px;
        color: @success;
      }

      .btn-submit {
        margin-top: 32px;
        color: rgba(255, 255, 255, 1);
        background: #1868e9;
      }
    }
  }
</style>
